<!-- 督办单统计表 -->
<template>
  <div class="lc_wrap">
    <el-row class="abnormalSummaryTable">

      <!-- 内容 -->
      <el-col :span="24" class="table-wrapper">
        <basic-container>

          <!-- 自定义搜索 -->
          <div class="search-tools">
            <div class="search-left">

              <!-- 开始日期 -->
              <el-date-picker
                v-model="dateFrom"
                type="date"
                size="small"
                placeholder="开始日期"
                :picker-options="pickerOption"
                value-format="yyyy-MM-dd">
              </el-date-picker>

              <!-- 联结字 -->
              <label class="search_label">
                至
              </label>

              <!-- 结束日期 -->
              <el-date-picker
                v-model="dateTo"
                type="date"
                size="small"
                placeholder="结束日期"
                :picker-options="pickerOption"
                value-format="yyyy-MM-dd">
              </el-date-picker>

              <!-- 环境局、运维公司 -->
              <el-radio-group v-model="entType">
                <el-radio-button 
                  v-for="(item, index) in entTypeOpt" 
                  :key="index" 
                  :label="item.label">
                </el-radio-button>
              </el-radio-group>

              <!-- 环保所、环保分局 -->
              <el-radio-group 
                class="environment_type" 
                v-model="environType" 
                v-if="!userInfo.isEnviron && entType === '环境局'"
              >
                <el-radio 
                  v-for="(item, index) in environTypeOpt" 
                  :key="index" 
                  :label="item.label">
                </el-radio>
              </el-radio-group>

            </div>

            <!-- 按钮   -->
            <div class="search-right">
              <el-button 
                class="search_btn" 
                type="primary" 
                size="small" 
                icon="el-icon-search" 
                @click="searchBtn">
                查 询
              </el-button>
              <el-button
                type="warning"
                size="small"
                plain
                icon="el-icon-download"
                @click="handleExport"
                v-if="this.permission.loam_summary_export">
                导 出
              </el-button>
            </div>

          </div>

          <!-- 表格内容 -->
          <avue-crud
            :option="option"
            :table-loading="loading"
            :data="tableData.filter((data) => data.deptName.includes(filterName))"
            ref="crud">
            <template slot="menuLeft" v-if="!userInfo.isEnviron">

              <!-- 环保局 -->
              <div class="environ_container">
                <el-select v-model="environId" placeholder="请选择" @change="changeEnviron">
                  <el-option
                    size="small"
                    v-for="(item, index) in environOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>

              <!-- 单位名称 -->
              <div class="filter_container">
                <el-input
                  placeholder="请输入单位名称"
                  prefix-icon="el-icon-search"
                  v-model="filterName">
                </el-input>
              </div>

            </template>
          </avue-crud>
        </basic-container>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { getUserInfo, getDeptList, getList } from "@/api/loam/abnormalSummary";
import { mapGetters } from "vuex";
import { dateFormat } from "@/util/date";
import { xlsxDownloadExl } from "@/util/exportExcel";

export default {
  data() {

    // 定义一个时间格式化函数
    Date.prototype.format = function(format) {
      var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(), 
        "s+": this.getSeconds(), 
        "q+": Math.floor((this.getMonth() + 3) / 3),
        S: this.getMilliseconds() 
      };
      if (/(y+)/.test(format)) {
        format = format.replace(
          RegExp.$1,
          (this.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      }

      return format;
    };

    return {
      pickerOption: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      allOption: {
        label: "全部",
        value: "all"
      },
      dateFrom: this.fun_date(-30),
      dateTo: dateFormat(new Date(), "yyyy-MM-dd"),
      entType: "环境局",
      environType: "按环保所查看",
      environId: "",
      filterName: "",
      userInfo: {isEnviron: false},
      entTypeOpt : [{
        label: "环境局",
        value: "1"
      }, {
        label: "运维公司",
        value: "2"
      }],
      environTypeOpt: [{
        label: "按环保所查看",
        value: "1"
      }, {
        label: "按分局查看",
        value: "2"
      }],
      environOptions: [],
      TOTAL_COUNT: "总计",
      loading: false,
      tableData: [],
      option: {
        columnBtn: false,
        menu: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        dialogClickModal: false,
        refreshBtn: false,
        index: true,
        selection: false,
        header: true,
        column: [{
          label: "单位名称",
          prop: "deptName",
          align: "center"
        }, {
          label: "总计督办单数",
          prop: "total",
          align: "center"
        }, {
          label: "已结束",
          prop: "processed",
          align: "center"
        }, {
          label: "占比（%）",
          prop: "proportionProcessed",
          align: "center"
        }, {
          label: "未结束",
          prop: "untreated",
          align: "center"
        }, {
          label: "占比（%）",
          prop: "untreatedProportion",
          align: "center"
        }, {
          label: "企业未处理",
          prop: "enterpriseNotProcessed",
          align: "center"
        }, {
          label: "占比（%）",
          prop: "proportionOfEnterprisesNotProcessed",
          align: "center"
        }, {
          label: "运维公司未处理",
          prop: "operationAndMaintenanceNotProcessed",
          align: "center"
        }, {
          label: "占比（%）",
          prop: "proportionOfUnprocessedOM",
          align: "center"
        }, {
          label: "环境分局未处理",
          prop: "notProcessedByTheEnvironmentalBureau",
          align: "center"
        }, {
          label: "占比（%）",
          prop: "percentageOfUnprocessedEnvironmentalBranch",
          align: "center"
        }]
      }
    };
  },
  computed: {
    ...mapGetters(["permission"])
  },
  watch: {

    // 开始日期
    dateFrom() {
      if (this.dateFrom) {
        let startDate = new Date(this.dateFrom);
        let endDate = new Date(this.dateTo);
        if (startDate.getTime() > endDate.getTime()) {
          this.dateTo = this.dateFrom;
        } else if (endDate.getTime() > startDate.getTime() + 30 * 24 * 60 * 60 * 1000) {
          startDate.setTime(startDate.getTime() + 30 * 24 * 60 * 60 * 1000);
          this.dateTo = dateFormat(new Date(startDate), "yyyy-MM-dd");
        }
      }
    },
    
    // 结束日期
    dateTo() {
      if (this.dateTo) {
        let startDate = new Date(this.dateFrom);
        let endDate = new Date(this.dateTo);
        if (startDate.getTime() > endDate.getTime()) {
          this.dateFrom = this.dateTo;
        } else if (endDate.getTime() - 30 * 24 * 60 * 60 * 1000 > startDate.getTime()) {
          endDate.setTime(endDate.getTime() - 30 * 24 * 60 * 60 * 1000);
          this.dateFrom = dateFormat(new Date(endDate), "yyyy-MM-dd");
        }
      }
    }
  },
  mounted() {
    this.onLoad();
  },
  methods: {

    // 搜索
    searchBtn() {
      this.AbnormalSummary();
    },

    // 环保局下拉框改值
    changeEnviron(value) {
      this.AbnormalSummary();
    },

    // 导出
    handleExport() {
      var routeName = "督办单统计表";
      var title = routeName + " " + this.dateFrom + "至" + this.dateTo;
      var cols = this.option.column;
      var tableData = this.tableData;
      xlsxDownloadExl(routeName, title, cols, tableData);
    },

    // 获取登录用户信息
    onLoad() {
      getUserInfo().then(res => {
        if(res.data.success !== true) {
          return;
        }
        this.userInfo.isEnviron = res.data.data;
      }).then(() => {
        this.getEnvironDept();
      });
    },

    // 获取环保分局列表
    getEnvironDept() {
      getDeptList().then(res => {
        if(res.data.success !== true) {
          return;
        }
        var resData = res.data.data;

        this.environOptions = [this.allOption];
        resData.forEach(item => {
          this.environOptions.push({
            label: item.deptName,
            value: item.id
          });
        });
        this.environId = this.allOption.value;
      }).then(() => {
        this.AbnormalSummary();
      });
    },

    // 获取督办单统清单
    AbnormalSummary() {
      this.loading = true;
      var startTime = this.dateFrom + " 00:00:00";
      var endTime = this.dateTo + " 23:59:59";
      var entType = "";
      this.entTypeOpt.forEach(item => {
        if(this.entType === item.label) {
          entType = item.value
        }
      });
      var environType = "-";
      if(this.entType === "环境局") {
        this.environTypeOpt.forEach(item => {
          if(this.environType === item.label) {
            environType = item.value;
          }
        });
      }
      var environId = this.environId === "all" ? "" : this.environId;

      getList(startTime, endTime, entType, environType, environId).then(res => {
        if (res.data.success !== true) {
          return;
        }
        var resData = res.data.data;

        // 将总计放在最后一行
        var dataList = [];
        resData.forEach(item => {
          if(item.deptName !== this.TOTAL_COUNT) {
            dataList.push(item);
          }
        });
        resData.forEach(item => {
          if(item.deptName === this.TOTAL_COUNT) {
            dataList.push(item);
          }
        });

        this.tableData = dataList;
        this.loading = false;
      });
    },

    // 补全时间
    formatNumber(num) {
      if(num < 10) {
        return "0" + num;
      }
      return num;
    },

    // 获取日期
    fun_date(num) {
      var date1 = new Date();
      var date2 = new Date( date1 );
      date2.setDate(date1.getDate() + num);
      var year = date2.getFullYear();
      var month = date2.getMonth() + 1;
      var day = date2.getDate();
      var time2 = year + "-" + this.formatNumber(month) + "-" + this.formatNumber(day);
      return time2;
    }
  }
};
</script>

<style lang="scss">
.abnormalSummaryTable {
  .el-table__empty-block {
    width: 100% !important;
  }
  .avue-crud__menu {
    margin-bottom: $avue-tabel-menu-btn_margin_bottom;
  }
  .search-tools {
    padding-left: 0 !important;
    height: auto !important;
    margin-bottom: 15px;
  }
  .el-card__body {
    height: calc(100% - 35px);
    .avue-crud {
      height: calc(100% - 155px);
    }
  }
  .table-wrapper {
    .el-card {
      overflow: scroll;
    }
  }
  .el-table__empty-block {
    width: 100% !important;
  }
  .el-table th > .cell {
    white-space: nowrap;
  }
  .el-table__fixed {
    height: calc(100% - 12px) !important;
  }
  .el-table__fixed-right {
    height: calc(100% - 12px) !important;
  }
  .el-radio-button__inner {
    padding: 8px 20px;
  }
  .el-radio-group {
    margin: 1px 0px 0px 15px;
    display: flex;
    align-items: center;
  }
  .el-radio-button:first-child .el-radio-button__inner,
  .el-radio-button:last-child .el-radio-button__inner {
    border-radius: 0px;
  }
  .el-radio {
    margin-right: 10px;
  }
  .environ_container {
    margin-bottom: 15px;
    .el-select .el-input__inner {
      height: 32px;
      line-height: 32px;
    }
    .el-select .el-input .el-select__caret {
      line-height: 32px;
    }
  }
  .filter_container {
    margin-bottom: 15px;
    .el-input__inner {
      height: 32px;
      line-height: 32px;
    }
    .el-input__icon {
      line-height: 32px;
    }
  }
  .avue-crud__pagination {
    display: none;
  }
  .avue-crud__menu {
    min-height: unset !important;
  }
}
</style>

<style lang="scss" scoped>
.el-row {
  height: calc(100% - 20px);
}

.el-col {
  height: 100%;
  overflow: auto;
}

.search-tools {
  height: 49px;
  display: flex;
  justify-content: space-between;
  padding: 0 8px;
}

.search-left {
  display: flex;
  height: 33px;
  line-height: 33px;
}

.search-right {
  display: flex;
}

.search_label{
  font-size: 14px;
  margin: 0px 10px;
}

.search_btn{
  margin-left: 10px;
}

.environ_container {
  width: 220px;
  float: left;
}

.filter_container {
  margin-left: 34px; 
  width: 220px; 
  float: left;
}
</style>